package com.dabai.qrtools.qrscanner.mlkit

import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import androidx.core.content.ContextCompat
import com.dabai.qrtools.qrscanner.R


class ScanOverlay(context: Context, attrs: AttributeSet?) : View(context, attrs) {

    private var paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private var paint2 = Paint(Paint.ANTI_ALIAS_FLAG)

    private var animator : ObjectAnimator? = null

    private var bitmap: Bitmap

    private var resultRect : RectF? = null

    private var showLine = true

    private var floatYFraction = 0f
    set(value) {field = value
    invalidate()}

    init {

        paint.style = Paint.Style.FILL_AND_STROKE
        paint.color = ContextCompat.getColor(context, R.color.iconScanOk)
        paint.strokeWidth = 17f.toPx().toFloat()

        paint2.style = Paint.Style.STROKE
        paint2.color = ContextCompat.getColor(context, R.color.white)
        paint2.strokeWidth = 3f.toPx().toFloat()

        bitmap = BitmapFactory.decodeResource(resources,R.drawable.icon_scan_line)
        getAnimator().start()
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        if (showLine){
            canvas?.drawBitmap(bitmap,(width - bitmap.width)/2f,height * floatYFraction,paint)
        }
        resultRect?.let {rect->
            canvas?.drawCircle(rect.left + (rect.right - rect.left)/2f,rect.top+(rect.bottom - rect.top)/2f,10f.toPx().toFloat(),paint)
            canvas?.drawCircle(rect.left + (rect.right - rect.left)/2f,rect.top+(rect.bottom - rect.top)/2f,17f.toPx().toFloat(),paint2)
        }

    }

    private fun getAnimator(): ObjectAnimator {
        if (animator == null) {
            animator = ObjectAnimator.ofFloat(
                this,
                "floatYFraction",
                0f,
                0.9f
            )
            animator?.duration = 4000
            animator?.repeatCount = -1 //-1代表无限循环
        }
        return animator!!
    }

    fun addRect(rect: RectF){
        showLine = false
        resultRect = rect
        getAnimator().cancel()
        invalidate()
    }


}